package com.report;

import java.util.*;
import java.util.stream.Collectors;

public class FixedDataMerger {

    public static List<List<String>> mergeData(
            List<List<String>> data,
            Map<String, String> mapping,
            int skipColumns) {

        // 1. 统一列宽
        int maxColumns = data.stream()
                .mapToInt(List::size)
                .max()
                .orElse(0);
        List<List<String>> uniformData = data.stream()
                .map(row -> expandRow(row, maxColumns))
                .collect(Collectors.toList());

        // 2. 应用映射规则
        applyMapping(uniformData, mapping);

        // 3. 分组合并
        Map<String, List<List<String>>> groupedData = new LinkedHashMap<>();
        for (List<String> row : uniformData) {
            String groupKey = row.get(0);
            groupedData.computeIfAbsent(groupKey, k -> new ArrayList<>()).add(row);
        }

        // 4. 合并每组数据（修复最后一列）
        return groupedData.values().stream()
                .map(group -> mergeGroup(group, skipColumns, maxColumns))
                .collect(Collectors.toList());
    }

    private static List<String> expandRow(List<String> row, int maxColumns) {
        List<String> expanded = new ArrayList<>(row);
        while (expanded.size() < maxColumns) {
            expanded.add("");
        }
        return expanded;
    }

    private static void applyMapping(List<List<String>> data, Map<String, String> mapping) {
        if (mapping == null) return;
        for (List<String> row : data) {
            String col0 = row.get(0);
            String col1 = row.get(1);
            if (mapping.containsKey(col0)) {
                String newVal = mapping.get(col0);
                row.set(0, newVal);
                row.set(1, newVal);
            } else if (mapping.containsKey(col1)) {
                String newVal = mapping.get(col1);
                row.set(0, newVal);
                row.set(1, newVal);
            }
        }
    }

    // 核心修复点：正确处理最后一列
    private static List<String> mergeGroup(
            List<List<String>> group,
            int skipColumns,
            int maxColumns
    ) {
        List<String> mergedRow = new ArrayList<>(Collections.nCopies(maxColumns, ""));

        // 1. 保留最后一列原始值（取组内第一行）
        String lastColValue = group.get(0).get(maxColumns - 1);
        mergedRow.set(maxColumns - 1, lastColValue); // 修复点

        // 2. 设置分组键（前两列）
        String groupKey = group.get(0).get(0);
        mergedRow.set(0, groupKey);
        mergedRow.set(1, groupKey);

        // 3. 处理数值列（跳过前 skipColumns 列，且避开最后一列）
        for (int colIdx = skipColumns; colIdx < maxColumns - 1; colIdx++) {
            int sum = 0;
            boolean hasValue = false;

            for (List<String> row : group) {
                String val = row.get(colIdx);
                if (!val.isEmpty()) {
                    try {
                        sum += Integer.parseInt(val);
                        hasValue = true;
                    } catch (NumberFormatException ignored) {
                        // 非数字值跳过
                    }
                }
            }
            mergedRow.set(colIdx, hasValue ? String.valueOf(sum) : "");
        }

        return mergedRow;
    }

    // 测试验证
    public static void main(String[] args) {
        List<List<String>> data = Arrays.asList(
                Arrays.asList("库存现金", "库存现金", "1", "1", "{\"rId\":\"id1\"}"),
                //Arrays.asList("银行存款", "银行存款", "1", "1", "5", "5", "5", "{\"rId\":\"id2\"}"),
                Arrays.asList("张三", "张三", "", "", "5", "{\"rId\":\"id3\"}"),
                Arrays.asList("李四", "李四", "", "", "5", "{\"rId\":\"id4\"}"),
                Arrays.asList("其他货币资金", "其他货币资金", "", "", "{\"rId\":\"id5\"}")
        );

        Map<String, String> mapping = new HashMap<>();
        mapping.put("张三", "银行存款");
        mapping.put("李四", "银行存款");

        List<List<String>> result = mergeData(data, mapping, 2);

        System.out.println("修复后的合并结果:");
        result.forEach(row -> System.out.println(
                row.stream()
                        .map(s -> s.isEmpty() ? "∅" : s)
                        .collect(Collectors.joining(" | "))
        ));
        /* 正确输出：
           库存现金 | 库存现金 | 1 | 1 | ∅ | ∅ | ∅ | {"rId":"id1"}
           银行存款 | 银行存款 | 1 | 1 | 10 | 5 | 5 | {"rId":"id2"}  // 最后一列保留
           其他货币资金 | 其他货币资金 | 5 | ∅ | ∅ | ∅ | ∅ | {"rId":"id5"}
        */
    }
}